<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2023-06-17
 * Time: 9:18
 */
namespace App\Services\User;
use App\CodeResponse;
use App\Exceptions\BusinessException;
use App\Models\User\Address;
use App\Services\BaseServices;

class AddressServices extends BaseServices
{
    public function getDefaultAddress($userId) {
        return Address::query()->where('user_id', $userId)
            ->where('is_default', 1)->first();
    }

    //获取用户地址列表
    public function getAddressListByUserId(int $userId) {
        return Address::query()->where("user_id", $userId)
            ->where("deleted", 0)->get();
    }

    // 获取用户详细地址
    public function getAddress($userId, $addressId) {
        return Address::query()->where("user_id", $userId)
            ->where("id", $addressId)
            ->where("deleted", 0)->first();
    }

    public function delete($userId, $addressId) {
        $address = $this->getAddress($userId, $addressId);
        if (is_null($address)) {
            $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL);
        }
        return $address->delete();
    }

    public function getAddressOrDefault($userId, $addressId = null) {
        if (empty($addressId)) {
            $address = AddressServices::getInstance()->getDefaultAddress($this->userId());
        } else {
            $address = AddressServices::getInstance()->getAddress($this->userId(), $addressId);
            if (empty($address)) {
                return $this->throwBadArgumentValue();
            }
        }
        return $address;
    }
}